
clear all
set more off

*cd /data2/cedsei/firm/

/* INPUTS */ 

local in_rams  	"/data2/cedsei/firm/rams_ourpop.dta"

/* OUTPUTS */ 

local out_chi  	"/data2/cedsei/firm/chi_panel_20230608.dta"

********************************************************************************

clear 
use "`in_rams'"

egen firm_yob = min(year), by(lopnr_peorgnr)
keep if inrange(year,2005,2018)
merge m:1 lopnr using /data2/cedsei/firm/yob, keep(3) nogen

merge 1:1 lopnr lopnr_peorgnr year using "/data2/cedsei/firm/notificatio_df"
gen months_on_notice = cond(_merge==3, ///
min(mantill_df,mantill)-manfran_df + 1,0)
replace months_on_notice = 0 if !mi(months_on_notice) & months_on_notice<0
gen months_df        = cond(_merge!=1,mantill_df - manfran_df +1 ,0)
drop manfran_df mantill_df _merge 

merge 1:1 lopnr lopnr_peorgnr year using "/data2/cedsei/firm/notificatio_dj"
gen months_dj        = cond(!mi(manfran_dj),mantill_dj - manfran_dj +1 ,0)
drop manfran_dj mantill_dj _merge 
replace months_on_notice=0 if mi(months_on_notice)
replace months_df=0 if mi(months_df)

merge 1:1 lopnr lopnr_peorgnr year using "/data2/cedsei/firm/notificatio_li"
gen months_djl        = cond(!mi(manfran_djl),mantill_djl - manfran_djl +1 ,0)
drop manfran_djl mantill_djl _merge 
replace months_on_notice=0 if mi(months_on_notice)
replace months_df=0        if mi(months_df)
replace months_dj=0        if mi(months_dj)

{ // New 20230608 
replace manfran = 1  if manfran==0 
replace mantill = 12 if mantill==0 

gen mearn = lonfink / tenure 

gen earn_month = cond(!mi(mearn),mearn,0)

gen wmonthsworked     = tenure*earn_month 
gen wmonths_on_notice = months_on_notice*earn_month 
gen wmonths_df        = months_df*earn_month 
gen wmonths_dj        = months_dj*earn_month 
gen wmonths_djl       = months_djl*earn_month 

}

replace tenure = 0 if mi(tenure)
gen age = (ym(year,1) - yob)/12

gen n_not = max(months_on_notice,months_df,months_dj)>0
gen n_nonnot = cond(n_not==0,1,0)

gcollapse (mean) cumten age (sum) n_not n_nonnot monthsworked=tenure months_on_notice months_df months_dj months_djl wmonthsworked wmonths_on_notice wmonths_df wmonths_dj wmonths_djl, by(lopnr_peorgnr year firm_yob nrofast)

gen s = n_not / (n_nonnot+n_not) 
gen chi      = months_on_notice   / monthsworked
gen chi_df   = months_df          / monthsworked
gen chi_dj   = months_dj          / monthsworked
gen chi_djl  = months_djl         / monthsworked
gen wchi     = wmonths_on_notice  / wmonthsworked
gen wchi_df  = wmonths_df         / wmonthsworked
gen wchi_dj  = wmonths_dj         / wmonthsworked
gen wchi_djl = wmonths_djl        / wmonthsworked
gen l_wmon = log(wmonthsworked)
gen l_mon = log(monthsworked)
drop if mi(l_mon)

egen m1 = total(n_not), by(lopnr_peorgnr)
keep if m1>0
drop m1

save "`out_chi'", replace
/*
binscatter chi chi_df if chi_df>0
binscatter chi chi_dj if chi_dj>0
*/

